<?php
namespace app\api\service;

use app\api\model\integral_goods;
use app\api\model\users;
use app\BaseController;
use think\facade\Db;

class IntegralService extends BaseController
{
    /**
     * SU ang
     * 积分 商品查询
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function integralSee()
    {
       $data =  integral_goods::with(['storeCoupon','mall'])->where('number','>=',1)->select()->toArray();
        return succeedHint($data,'积分兑换商品');
    }

    /**
     * Su ang
     * 积分兑换 接口
     * @param $uid 用户id
     * @param $integral_id 积分活动商品 id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function integralCoin($uid,$integral_id)
    {
        $data = integral_goods::where('id',$integral_id)->find()->toArray();
        //兑换所需要的积分
        $credits_exchange = $data['credits_exchange'];
       $user = users::where('uid',$uid)->find()->toArray();
       //用户积分
        $points = $user['points'];
        if ($points>=$credits_exchange){
            Db::startTrans();
            try{
                users::where('uid',$uid)->dec('points',$credits_exchange)->update();
                integral_goods::where('id',$integral_id)->dec('number',1)->update();
                //兑换成功 生成订单
                Db::commit();
                return succeedHint('','兑换成功');
            } catch (\Exception $e) {
                Db::rollback();
                return errorHint('未知错误');
            }

        }else{
            return errorHint('积分不足，攒够积分再来吧');
        }
    }
}